﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MiniX.API.Data;
using MiniX.Models;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Senparc.CO2NET.Extensions;
using MiniX.Utility.Helper;

namespace MiniX.API.Controllers
{
    /// <summary>
    /// 消息类，定义了CURD相关操作
    /// </summary>
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class MessagesController : BaseController<MessagesController>
    {
        /// <summary>
        /// MessagesController
        /// </summary>
        public MessagesController(MiniXApiContext context, IHttpContextAccessor httpContextAccessor) : base(context, httpContextAccessor)
        {

        }

        /// <summary>
        /// 分页显示消息数据
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="limit">每页显示数量</param>
        /// <returns></returns>
        [HttpGet]
        [Route("/api/messages")]
        public async Task<IActionResult> GetByPage(int page, int limit, long member_id)
        {
            try
            {
                var result = from item in _context.Set<Messages>().Where(t => t.member_id == member_id)
                             select new
                             {
                                 item.message_id,
                                 item.object_id,
                                 item.object_type_id,
                                 object_type_name = item.object_type_id > 0 ? _context.mini_objects.FirstOrDefault(t => t.object_id == item.object_type_id)!.object_name : "",
                                 item.type_id,
                                 type_name = item.type_id > 0 ? _context.mini_message_types.FirstOrDefault(t => t.type_id == item.type_id)!.type_name : "-",
                                 item.member_id,
                                 item.to_member_id,
                                 item.message_title,
                                 item.message_content,
                                 item.message_img,
                                 item.is_read,
                                 item.message_remark,
                                 item.created_at,
                                 format_time = item.created_at.ToString("yyyy-MM-dd HH:mm")
                             };
                var list = await result.OrderByDescending(t => t.message_id).Skip((page - 1) * limit).Take(limit).ToListAsync();
                var count = result.LongCount();
                if (count <= 0)
                {
                    return Json(new { code = 0, msg = "暂无数据", count = 0 });
                }
                else
                {
                    return Json(new { code = 0, msg = "success", data = list, page = page, limit = limit, count = count, total_page = count / limit });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> GetDataByPage");
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.List, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取消息详情
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns>返回消息详情</returns>
        [HttpGet("/api/messages/{id}")]
        public async Task<IActionResult> GetById(long id)
        {
            try
            {
                log.Information("id=" + id);
                var result = await _context.mini_messages.Where(t => t.message_id == id).Select(item => (new
                {
                    item.message_id,
                    item.object_id,
                    item.object_type_id,
                    object_type_name = item.object_type_id > 0 ? _context.mini_objects.FirstOrDefault(t => t.object_id == item.object_type_id)!.object_name : "-",
                    item.type_id,
                    type_name = item.type_id > 0 ? _context.mini_message_types.FirstOrDefault(t => t.type_id == item.type_id)!.type_name : "-",
                    item.member_id,
                    item.to_member_id,
                    item.message_title,
                    item.message_content,
                    item.message_img,
                    item.is_read,
                    item.message_remark,
                    item.created_at,
                    format_time = item.created_at.ToString("yyyy-MM-dd HH:mm")
                })).FirstOrDefaultAsync();
                if (result == null)
                {
                    return Json(new { code = 0, msg = "数据为空", count = 0 });
                }
                else
                {
                    return Json(new { code = 0, msg = "success", data = result });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Details");
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Select, errmsg = ex.Message });
            }
        }


        /// <summary>
        /// 获取会员未读消息数量
        /// </summary>
        /// <param name="member_id"></param>
        /// <returns></returns>
        [HttpGet("/api/messages/count")]
        public IActionResult Count(long member_id)
        {
            try
            {
                log.Information("member_id=" + member_id);

                var data = new
                {
                    message_num = _context.mini_messages.Where(t => t.member_id == member_id && !t.is_read).Count(),
                };

                return Json(new { code = 0, msg = "success", data = data });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Details");
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Select, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 新增消息
        /// </summary>
        /// <param name="messages">构造消息对象数据</param>
        /// <returns>返回新增的消息</returns>          
        [HttpPost]
        [Route("/api/messages")]
        public async Task<IActionResult> Create(Messages messages)
        {
            try
            {
                log.Information("messages=" + messages.ToJson());
                messages.created_at = DateTime.Now;
                _context.mini_messages.Add(messages);
                await _context.SaveChangesAsync();
                return Json(new { code = 0, msg = "success", data = messages });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Create");
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Create, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID更新消息-PC
        /// </summary>
        /// <param name="messages">构造消息对象数据</param>
        /// <returns></returns>
        [HttpPost]
        [Route("/api/messages/update")]
        public async Task<IActionResult> Update(Messages messages)
        {
            try
            {
                log.Information("messages=" + messages.ToJson());
                var item = _context.mini_messages.FirstOrDefault(c => c.message_id == messages.message_id);
                if (item != null)
                {
                    item.is_read = true;
                    _context.mini_messages.Update(item);
                    await _context.SaveChangesAsync();
                }

                return Json(new { code = 0, msg = "操作成功" });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Update");
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Update, errmsg = ex.Message });
            }
        }
    }
}
